package com.wdc;

import com.alibaba.fastjson.JSON;
import com.wdc.annotation.DoWhitelist;
import org.apache.commons.beanutils.BeanUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@Aspect
@Component
public class DoJoinPoint {

    private Logger logger = LoggerFactory.getLogger(DoJoinPoint.class);

    @Resource
    private String whiteListConfig;


    @Pointcut("@annotation(com.wdc.annotation.DoWhitelist)")
    public void aopPoint() {

    }

    @Around("aopPoint()")
    public Object doRouter(ProceedingJoinPoint jp) throws Throwable {
        //获取内容
        Method method = getMethod(jp);
        DoWhitelist whitelist = method.getAnnotation(DoWhitelist.class);

        //获取字段值
        String keyValue = getFiledValue(whitelist.key(), jp.getArgs());
        if (null == keyValue || "".equals(keyValue)) {
            return jp.proceed();
        }

        String[] split = whiteListConfig.split(",");
        //白名单过滤
        for (String string : split) {
            if (keyValue.equals(string)) {
                return jp.proceed();
            }
        }



        return  returnObject(whitelist, method);
    }

    private Object returnObject(DoWhitelist whitelist, Method method) throws InstantiationException, IllegalAccessException {
        Class<?> returnType = method.getReturnType();
        String returnJson = whitelist.returnType();
        if ("".equals(returnJson)) {
            return returnType.newInstance();
        }
        return JSON.parseObject(returnJson, returnType);

    }

    private String getFiledValue(String filed, Object[] args) {
        String keyValue = null;
        for (Object arg : args) {
            try {
                if (null == keyValue || "".equals(keyValue)) {
                    keyValue = BeanUtils.getProperty(arg, filed);
                } else {
                    break;
                }
            } catch (Exception e) {
                if (args.length == 1) {
                    return args[0].toString();

                }

            }
        }

        return keyValue;
    }

    private Method getMethod(ProceedingJoinPoint jp) throws NoSuchMethodException {
        Signature sig = jp.getSignature();
        MethodSignature methodSignature = (MethodSignature) sig;
        return jp.getTarget().getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
    }


}
